<!--
 * @Author: 梁青春
 * @Date: 2025-11-04 15:20:00
 * @LastEditors: 梁青春
 * @Description: 遗嘱下达设置 - 双Tab主页面（下达规则设置 / 开出规则设置）
-->
<template>
   <navbar />
  <div class="main-container order-issue-settings">
    <!-- 双Tab布局 -->
    <el-card class="tabs-card">
      <el-tabs v-model="activeTab" class="rule-tabs">
        <!-- Tab1：下达规则设置 -->
        <el-tab-pane label="下达规则设置" name="issueRule">
          <div class="table-container">
            <!-- 只有在“下达规则设置”Tab展示新增按钮 -->
            <el-button
              v-hasPermi="['baseinfo:orderIssueSettings:add']"
              type="primary"
              icon="Plus"
              @click="handleAddRule"
              class="add-btn op-btn"
            >
              新增规则
            </el-button>
            <div class="table-container">
              <el-table
                :data="ruleList"
                stripe
                border
                style="width: 100%"
                v-loading="loading"
                empty-text="暂无规则数据"
                class="rule-table"
              >
                <!-- 药品类型 -->
                <el-table-column prop="drugType" label="药品类型" min-width="120" align="center" />

                <!-- 中药加工：非中药显示 '-' -->
                <el-table-column prop="tcmProcess" label="中药加工" width="120" align="center">
                  <template #default="scope">
                    <span>{{ scope.row.tcmProcess || '-' }}</span>
                  </template>
                </el-table-column>

                <!-- 来源科室 -->
                <el-table-column prop="sourceDept" label="来源科室" min-width="160" align="center" />

                <!-- 病区 -->
                <el-table-column prop="ward" label="病区" min-width="140" align="center" />

                <!-- 下达至 -->
                <el-table-column prop="deliverTo" label="下达至" width="120" align="center" />

                <!-- 状态列，显示已启用/已停用，并为非默认规则展示提示文字 -->
                <el-table-column prop="status" label="状态" width="140" align="center">
                  <template #default="scope">
                    <el-tag :type="scope.row.enabled ? 'success' : 'info'">
                      {{ scope.row.enabled ? '已启用' : '已停用' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 分页组件 -->
            <div class="queryParams-container">
              <pagination
                v-show="total > 0"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                :total="total"
                @query-params="getList"
              />
            </div>
          </div>
        </el-tab-pane>

        <!-- Tab2：开出规则设置 -->
        <el-tab-pane label="开出规则设置" name="prescribeRule">
          <div class="settings-container">
            <el-button type="primary" @click="handleSaveSettings" :loading="saveSettingsLoading" class="add-btn op-btn">
              保存
            </el-button>
            <el-form :model="settingsForm" label-width="180px" class="settings-form">
              <div class="section-title">开出规则</div>

              <!-- 库存不足的药品处理规则 -->
              <el-form-item label="库存不足的药品">
                <!-- 单选：三种策略；纵向排列每行一个 -->
                <el-radio-group v-model="settingsForm.insufficientStockBehavior" class="radio-group-vertical">
                  <el-radio value="allow_hint">允许开出，同时系统会提醒库存不足</el-radio>
                  <el-radio value="allow_nohint">允许开出，系统不做任何提示</el-radio>
                  <!-- 为括号内说明文字添加浅灰色，并在选中时保持浅灰 -->
                  <el-radio value="deny">
                    不允许开出
                    <span class="radio-desc">（进价加成商品库存不足时始终不允许开出）</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 过期药品处理规则 -->
              <el-form-item label="过期的药品">
                <!-- 纵向排列每行一个 -->
                <el-radio-group v-model="settingsForm.expiredDrugBehavior" class="radio-group-vertical">
                  <el-radio value="no_hint">开出时系统不做任何警示</el-radio>
                  <!-- 右侧提示文字按设计图浅灰显示，选中依旧浅灰 -->
                  <el-radio value="exclude">
                    开出时系统剔除过期药品，
                    <span class="radio-desc">若变更规则，次日生效</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <div class="section-title">锁库规则</div>

              <!-- 门诊锁定库存 -->
              <el-form-item label="门诊锁定库存">
                <!-- 纵向排列每行一个；保持与原型一致 -->
                <el-radio-group v-model="settingsForm.outpatientLock" class="radio-group-vertical">
                  <el-radio value="none">不锁定</el-radio>
                  <el-radio value="after_charge">
                    <!-- 括号说明文本浅灰显示，提升可读性 -->
                    收费后锁定库存
                    <span class="radio-desc">（收费后锁定库存量以备发药，关闭发药单或退费后解除锁定）</span>
                  </el-radio>
                  <el-radio value="after_order">
                    开单后锁定库存
                    <span class="radio-desc">（开单后锁定库存量以备发药，关闭发药单或退费后解除锁定）</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 住院锁定库存 -->
              <el-form-item label="住院锁定库存">
                <!-- 纵向排列每行一个 -->
                <el-radio-group v-model="settingsForm.inpatientLock" class="radio-group-vertical">
                  <el-radio value="none">不锁定</el-radio>
                  <el-radio value="after_verify">
                    核对医嘱后锁定库存
                    <span class="radio-desc">（核对医嘱生效行任务后锁定库存，撤销医嘱或药房拒发后解除锁定）</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup name="OrderIssueSettings">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { mockOrderIssueApi } from '@/mock/orderIssue'

const proxy = getCurrentInstance().proxy
const router = useRouter()

// 当前激活的Tab
const activeTab = ref('issueRule')

// 列表页相关状态
const loading = ref(false)
const ruleList = ref([])
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
})

// 开出规则设置表单
const saveSettingsLoading = ref(false)
const settingsForm = reactive({
  insufficientStockBehavior: 'allow_hint', // 库存不足策略
  expiredDrugBehavior: 'no_hint', // 过期药品策略
  outpatientLock: 'after_order', // 门诊锁库策略
  inpatientLock: 'after_verify' // 住院锁库策略
})

// 加载下达规则列表（模拟接口）
const loadRuleList = async () => {
  try {
    loading.value = true
    const res = mockOrderIssueApi.getIssueRuleList({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    })
    if (res.code === 200) {
      ruleList.value = res.data.list
      total.value = res.data.total
    } else {
      proxy.$modal.notifyWarning(res.message || '获取规则列表失败')
    }
  } catch (error) {
    console.error('获取规则列表失败:', error)
    proxy.$modal.notifyWarning('获取规则列表失败')
  } finally {
    loading.value = false
  }
}

// 切换启用状态
const toggleStatus = row => {
  try {
    const updated = mockOrderIssueApi.toggleRuleStatus(row.id)
    if (updated.code === 200) {
      proxy.$modal.notifySuccess('状态已更新')
      loadRuleList()
    } else {
      proxy.$modal.notifyWarning(updated.message || '更新状态失败')
    }
  } catch (error) {
    console.error('更新状态失败:', error)
    proxy.$modal.notifyWarning('更新状态失败')
  }
}

// 删除规则
const handleDelete = async row => {
  try {
    await proxy.$modal.confirm(`确定要删除规则“${row.drugType}”吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = mockOrderIssueApi.deleteIssueRule(row.id)
    if (res.code === 200) {
      proxy.$modal.notifySuccess(res.message || '删除成功')
      loadRuleList()
    } else {
      proxy.$modal.notifyWarning(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      proxy.$modal.notifyWarning('删除失败')
    }
  }
}

// 新增规则 -> 跳转到新增表单页面
const handleAddRule = () => {
  router.push('/baseinfo/orderIssueSettings/add')
}

// 保存开出规则设置
const handleSaveSettings = async () => {
  try {
    saveSettingsLoading.value = true
    const res = mockOrderIssueApi.savePrescribeSettings({ ...settingsForm })
    if (res.code === 200) {
      proxy.$modal.notifySuccess('设置已保存')
    } else {
      proxy.$modal.notifyWarning(res.message || '保存失败')
    }
  } catch (error) {
    console.error('保存开出规则设置失败:', error)
    proxy.$modal.notifyWarning('保存开出规则设置失败')
  } finally {
    saveSettingsLoading.value = false
  }
}

// 获取列表数据的方法别名，用于分页组件
const getList = () => {
  loadRuleList()
}

// 组件挂载时加载数据
onMounted(() => {
  loadRuleList()
})
</script>

<style lang="scss" scoped>
.order-issue-settings {
  .add-btn {
    margin-bottom: 12px;
  }

  .tabs-card {
    .rule-tabs {
      --el-tabs-header-height: 40px;
    }
  }

  .non-default-tip {
    margin-left: 8px;
    color: #f56c6c;
    font-size: 12px;
  }

  .settings-container {
    padding: 8px 4px 16px;

    .section-title {
      margin: 4px 0 12px;
      font-weight: 600;
      font-size: 14px;
    }

    .save-section {
      margin-top: 16px;
      text-align: left;
    }
  }

  // 将单选组纵向排列，每行一个选项（scoped 样式）
  .radio-group-vertical {
    display: flex;
    flex-direction: column; // 纵向
    align-items: flex-start;
    gap: 6px; // 行间距

    // 覆盖 Element Plus 默认的右侧外边距，使视觉更紧凑
    :deep(.el-radio) {
      margin-right: 0;
    }
  }

  // Radio 标签内的括号说明文字：浅灰色显示，选中依旧保持浅灰
  // 使用 :deep 选择器确保可以覆盖 Element Plus 选中态主色
  :deep(.el-radio__label .radio-desc) {
    color: var(--el-text-color-secondary); // 主题的次级文字色（浅灰）
  }
  :deep(.el-radio.is-checked .el-radio__label .radio-desc) {
    color: var(--el-text-color-secondary) !important; // 选中态也保持浅灰
  }
}
</style>
